package org.ndot.java.util.concurrent;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * 【小蚂蚁学堂 - J2SE_Study】
 * 
 * 项目名称：J2SE_Study
 * 
 * 文件名：TestBlockQueue.java
 * 
 * 功 能:
 * 
 * 
 * 作 者: SunJincheng
 * 
 * 创建时间: 2010-4-8
 * 
 */
public class TestBlockQueue {
	@SuppressWarnings("unchecked")
	public static void main(String[] args) {

		BlockingQueue q = new ArrayBlockingQueue(1);

		Producer p = new Producer(q);

		Consumer c1 = new Consumer(q);

		Consumer c2 = new Consumer(q);

		new Thread(p).start();

		new Thread(c1).start();

		new Thread(c2).start();

	}

}

class Producer implements Runnable {

	private final BlockingQueue queue;

	Producer(BlockingQueue q) {

		queue = q;

	}

	public void run() {

		try {

			for (int i = 0; i < 3; i++) {

				queue.put(produce());

				System.out.println("生产后：" + queue.peek());

			}

		} catch (InterruptedException ex) {

			ex.printStackTrace();

		}

	}

	Character produce() {

		char c = (char) (Math.random() * 26 + 'A');

		System.out.println("生产前：" + c);

		return c;

	}

}

/**
 * 
 * 消费者
 */

class Consumer implements Runnable {

	private final BlockingQueue<Character> queue;

	@SuppressWarnings("unchecked")
	Consumer(BlockingQueue q) {

		queue = q;

	}

	public void run() {

		try {

			while (true) {

				consume((Character) queue.take());

				 Thread.sleep(100);

			}

		} catch (InterruptedException ex) {

			ex.printStackTrace();

		}

	}

	void consume(Character c) {

		System.out.println("消费：" + c);

	}

}
